import { Injectable } from '@angular/core';
import { _HttpClient } from '@delon/theme';
import { Observable } from 'rxjs';
import { HttpResponse } from '@angular/common/http';
import { QueryOptions } from 'src/app/project/model/common/query-options';
import { ApiPagedData } from 'src/app/project/model/common/api-paged-data';
import { SystemFileDTO } from 'src/app/project/model/icm/icm-global/system-file/system-file-dto';

@Injectable({
  providedIn: 'root',
})
export class SystemFileService {
  /**
   * API的入口URL
   */
  private static URL = '/api/files';

  constructor(private http: _HttpClient) {}

  /**
   * 分页查询文件
   * @param options 分页参数
   * @param originalName 文件原始名称
   * @param type 文件类型
   */
  getFiles(options: QueryOptions, originalName?: string, type?: string): Observable<ApiPagedData<SystemFileDTO>> {
    const params = {};
    Object.assign(params, options, originalName ? { originalName } : {}, type ? { type } : {});
    return this.http.get<ApiPagedData<SystemFileDTO>>(SystemFileService.URL, params);
  }

  /**
   * 取指定文件
   * @param fileId 文件id
   */
  getFileById(fileId: string): Observable<SystemFileDTO> {
    return this.http.get<SystemFileDTO>(`${SystemFileService.URL}/${fileId}`);
  }

  /**
   * 删除指定文件
   * @param fileId 文件id
   */
  deleteFileById(fileId: string): Observable<any> {
    return this.http.delete(`${SystemFileService.URL}/${fileId}`);
  }

  /**
   * 取指定文件的内容, 通常用于页面直接显示图片等文件的内容
   * @param fileId 文件id
   */
  getFileContentById(fileId: string): Observable<HttpResponse<Blob>> {
    return this.http.get(`${SystemFileService.URL}/${fileId}/content`, null, {
      responseType: 'blob',
      observe: 'response',
    });
  }

  /**
   * 下载指定文件, 触发browser显示保存对话框
   * @param fileId 文件名称
   */
  downloadFileContentById(fileId: string): Observable<HttpResponse<Blob>> {
    return this.http.get(`${SystemFileService.URL}/${fileId}/download`, null, {
      responseType: 'blob',
      observe: 'response',
    });
  }

  /**
   * 预览指定文件(转成pdf后预览)
   * @param fileId 文件名称
   */
  previewFileById(fileId: string): Observable<HttpResponse<Blob>> {
    return this.http.get(`${SystemFileService.URL}/${fileId}/preview`, null, {
      responseType: 'blob',
      observe: 'response',
    });
  }

  /**
   * 上传多个文件
   * @param files 文件
   * @param type 文件类型
   */
  uploadMultipleFiles(files: FormData, type: string): Observable<Array<SystemFileDTO>> {
    return this.http.post<Array<SystemFileDTO>>(`${SystemFileService.URL}/multiple?type=${type}`, files);
  }

  /**
   * 上传单个个文件
   * @param type 文件类型
   * @param file 文件
   */
  singleFile(type: string, file: FormData): Observable<SystemFileDTO> {
    return this.http.post<SystemFileDTO>(`${SystemFileService.URL}/single?type=${type}`, file);
  }
}
